import Vue from 'vue'
import VueI18n from 'vue-i18n'

import { getLanguage } from '@/utils/cookies'

/**
 * 'zh-cn'   => 1, // 简体中文
 'en-us'   => 2, // 英语
 'zh-tw'   => 3, // 繁体中文
 'ru-ru'   => 4, // 俄语
 'ko'      => 5, // 韩语
 'ja'      => 6, // 日语
 'de'      => 7, // 德语
 'pt'      => 8, // 葡萄牙语
 'th'      => 9, // 泰语
 'vi'      => 10, // 越南语
 */

// element-ui built-in lang
import elementEnLocale from 'element-ui/lib/locale/lang/en'
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'
import elementZhTwLocale from 'element-ui/lib/locale/lang/zh-TW'
import elementRuRuLocale from 'element-ui/lib/locale/lang/ru-RU'
import elementKoLocale from 'element-ui/lib/locale/lang/ko'
import elementJaLocale from 'element-ui/lib/locale/lang/ja'
import elementDeLocale from 'element-ui/lib/locale/lang/de'
import elementPtLocale from 'element-ui/lib/locale/lang/pt'
import elementThLocale from 'element-ui/lib/locale/lang/th'
import elementViLocale from 'element-ui/lib/locale/lang/vi'

Vue.use(VueI18n)
function loadLocaleMessages() {
  const locales = require.context('./', true, /[A-Za-z0-9-_,\s]+\.js$/i)
  const messages = {
    'zh-cn': { ...elementZhLocale }, // 简体中文
    'en-us': { ...elementEnLocale }, // 英语
    'zh-tw': { ...elementZhTwLocale }, // 繁體中文
    'ru-ru': { ...elementRuRuLocale }, // 俄语
    'ko': { ...elementKoLocale }, // 韩语
    'ja': { ...elementJaLocale }, // 日语
    'de': { ...elementDeLocale }, // 德语
    'pt': { ...elementPtLocale }, // 葡萄牙语
    'th': { ...elementThLocale }, // 泰语
    'vi': { ...elementViLocale } // 越南语
  }

  locales.keys().forEach(key => {
    const matched = key.match(/([A-Za-z0-9-_]+)\//i)
    const matchedName = key.match(/([A-Za-z0-9-_]+)\./i)

    if (matched && matched.length > 1) {
      const locale = matched[1]
      messages[locale][matchedName[1]] = locales(key).default
    }
  })
  return messages
}
// const messages = {
//   en: {
//     ...enLocale,
//     ...elementEnLocale
//   },
//   zh: {
//     ...zhLocale,
//     ...elementZhLocale
//   }
// }
const messages = loadLocaleMessages()

export const getLocale = () => {
  const cookieLanguage = getLanguage()

  if (cookieLanguage && cookieLanguage !== 'undefined') {
    document.documentElement.lang = cookieLanguage
    return cookieLanguage
  }

  const language = navigator.language.toLowerCase()

  const locales = Object.keys(messages)
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      document.documentElement.lang = locale
      return locale
    }
  }

  // Default language
  const defaultLanguage = 'zh-cn'
  document.documentElement.lang = defaultLanguage
  return defaultLanguage
}

const i18n = new VueI18n({
  locale: getLocale(),
  messages
})

export default i18n
